#ifndef F0981FA1_F593_4183_BFD9_28C7CBCAA9F5
#define F0981FA1_F593_4183_BFD9_28C7CBCAA9F5


#endif /* F0981FA1_F593_4183_BFD9_28C7CBCAA9F5 */

// 第五步，编写TCP服务端

#include <string>
#include <signal.h>
#include <functional>
#include "Log.hpp"
#include "Socket.hpp"

using func_t = std::function<std::string(std::string&)>;

class TcpServer
{
public:
    TcpServer(uint16_t port, func_t callback)
        :port_(port),callback_(callback)
    {}
    ~TcpServer()
    {}
public:
    bool InitServer()   // 初始化服务器
    {
        listensock_.Socket();       // 创建
        listensock_.Bind(port_);    // 绑定
        listensock_.Listen();       // 监听
        lg(Info, "Init server success...");
        return true;
    }    
    
    bool Start()    // 开始处理
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);

        while (true)        // 服务器一直运行中
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = listensock_.Accept(&clientip, &clientport);    // 服务端建立接收链接
            if(sockfd < 0)
                continue;
            // 服务端建立接收链接成功
            lg(Info, "accept a new link, sockfd: %d, clientip: %s, clientport: %d", sockfd, clientip.c_str(), clientport);

            // 服务端开始提供服务
            if(fork() == 0)
            {
                // child
                listensock_.Close();            // ?
                std::string inbuffer_stream;
                
                // 数据计算
                while (true)
                {   
                    char buffer[1024];
                    ssize_t n = read(sockfd, buffer, sizeof(buffer));
                    if(n > 0)
                    {
                        buffer[n] = 0;
                        inbuffer_stream += buffer;

                    }
                    else 
                        break;
                }
                exit(0);                
            }
            close(sockfd);
        }
    }
private:
    uint16_t port_;
    Sock listensock_;
    func_t callback_;
};

